<?php

class Default_Cron_Default_Store implements Kernel_Filter_Interface
{

	/**
	 *
	 * @var Default_Model_Data
	 */
	private $_model;

	public function __construct()
	{
		$this->_model = Default_Model_Data::getInstance();
	}

	/**
    * Start filter.
    *
    */
    public function process()
	{
		$affected_rows = $this->_setValues(
				$this->_getValues($this->_model->getLastDrawing()));
		
		Application::getResponse()
			->writeln('Inserted ' . $affected_rows . ' new drawings');
	}

	private function _setValues($values)
	{
		$affected_rows = 0;

		if (!empty($values)) {
			$affected_rows = $this->_model->setData($values);
		}

		return $affected_rows;
	}

	private function _getValues($last_drawing)
	{
		$values = array();

		$handle = fopen(Kernel_Config::get('default', 'file'), 'r');
		if (!$handle) {
			trigger_error('No file', E_USER_ERROR);
		}
		$i = 0;
		while (false !== ($row = fgetcsv($handle, null, ';'))) {
			$i ++;

			// meta info
			if (1 == $i) {
				continue;
			}

			// add only unexisting drawings
			if ($row[0] > $last_drawing) {
				$row[1] = date('Y-m-d', strtotime($row[1]));
				$values[] = $row;
			}

		}

		fclose($handle);

		return $values;
	}

}